package net.maxwoods.nimble.spring.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;

@Controller
public class LoginController {

    private static final Logger logger=LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(value = "/login")
    public ModelAndView login(ServletRequest request) {
        String code=request.getParameter("code");
        String error=request.getParameter("error");
        String logout=request.getParameter("logout");
        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "不正确的用户名和密码");
        }
        if (logout != null) {
            model.addObject("msg", "你已经成功退出");
        }
        model.setViewName("login");
        return model;
    }

    /**
     * 登录成功处理器
     * @return
     */
    @RequestMapping(value="/loginSuccess",method=RequestMethod.GET)
    public @ResponseBody
    boolean loginSuccess(){
        return true;
    }
    /**
     * 登录失败处理器
     * @return
     */
    @RequestMapping(value="/loginFaild",method=RequestMethod.GET)
    public @ResponseBody boolean loginFaild(){
        return false;
    }

    @RequestMapping("/test")
    public String test(Model model)
    {
        for(GrantedAuthority grantedAuthority:SecurityContextHolder.getContext().getAuthentication().getAuthorities())
        {
            logger.info(grantedAuthority.toString());
        }
        return "/test";
    }
}
